<template>
  <div>
    <vxe-modal
      :title="modalTitle"
      v-model="show"
      :loading="loading"
      :mask="false"
      :lock-view="false"
      width="1000px"
      height="740px"
      destroy-on-close
      show-zoom
      remember
      resize
      show-footer
    >
      <el-form
        ref="refForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        @submit.prevent
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane
            :label="$t('menu.dev.menu.tabs.base', '基本信息')"
            name="basic"
          >
            <!-- 基本信息 -->
            <div class="form-section">
              <el-row :gutter="20">
                <!-- 菜单类型 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.type', '类型')"
                    prop="type"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.type',
                        '系统菜单分为目录、菜单、外链和IFRAME四种类型',
                      )
                    "
                  >
                    <ra-dict-select
                      v-model="formData.type"
                      code="sys_menu_type"
                      type="radio"
                      :disabled="isEditMode"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 父菜单 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.pid', '父菜单')"
                    prop="pid"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.pid',
                        '菜单必须具有父目录或者父菜单',
                      )
                    "
                  >
                    <ra-dict-tree-select
                      ref="refPid"
                      v-model="formData.pid"
                      code="sys_menu_tree_options"
                      type="tree-select"
                      check-strictly
                      :default-expanded-keys="[0]"
                    ></ra-dict-tree-select>
                  </el-form-item-plus>
                </el-col>
                <!-- 菜单名称 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.name', '名称')"
                    prop="name"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.name',
                        '菜单名称是用于显示在菜单栏上面的名称；如果采用多语言则此处仅定义键名。',
                      )
                    "
                  >
                    <el-input
                      v-model="formData.name"
                      :placeholder="$p('menu.dev.menu.field.name', '名称')"
                      maxlength="50"
                      show-word-limit
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 后端控制器 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.controller', '控制器')"
                    prop="controller"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.controller',
                        '请输入后端为前端提供数据的控制器类的完整名称',
                      )
                    "
                  >
                    <el-input
                      v-model="formData.controller"
                      placeholder="System/User"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 图标选择器 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.icon', '图标')"
                    prop="icon"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.icon',
                        '设置菜单在菜单栏显示时左侧的图标',
                      )
                    "
                  >
                    <icon-select v-model="formData.icon" />
                  </el-form-item-plus>
                </el-col>
                <!-- 显示菜单 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    prop="visible"
                    :label="$t('menu.dev.menu.field.visible', '显示')"
                    :tooltipContent="
                      $t('menu.dev.menu.tip.visible', '是否允许显示在菜单栏中')
                    "
                  >
                    <ra-dict-select
                      v-model="formData.visible"
                      code="status_options"
                      type="radio"
                    />
                  </el-form-item-plus>
                </el-col>

                <!-- 多语言 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.lang', '多语言')"
                    prop="disable_lang"
                    :tooltipContent="$t('menu.dev.menu.tip.lang', '支持多语言')"
                  >
                    <el-radio-group v-model="formData.lang">
                      <el-radio :value="1">启用</el-radio>
                      <el-radio :value="0">禁止</el-radio>
                    </el-radio-group>
                  </el-form-item-plus>
                </el-col>
                <!-- 启用数据权限 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.permission', '数据权限')"
                    prop="disable_lang"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.permission',
                        '启用数据权限后，此菜单的查询将根据用户数据权限确定查询结果；',
                      )
                    "
                  >
                    <el-radio-group v-model="formData.permission">
                      <el-radio :value="1">启用</el-radio>
                      <el-radio :value="0">禁止</el-radio>
                    </el-radio-group>
                  </el-form-item-plus>
                </el-col>
                <!-- 排序号 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('common.field.sort', '排序')"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.sort',
                        '默认可以留空，系统会自动设置排序号',
                      )
                    "
                    prop="sort"
                  >
                    <el-input-number
                      v-model="formData.sort"
                      controls-position="right"
                      :min="0"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 状态 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    prop="status"
                    :label="$t('common.field.status', '状态')"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.status',
                        '设置菜单状态，禁用则不可用',
                      )
                    "
                  >
                    <ra-dict-select
                      v-model="formData.status"
                      code="status_options"
                      type="radio"
                    />
                  </el-form-item-plus>
                </el-col>
              </el-row>
            </div>

            <!-- 菜单 -->
            <div shadow="always" class="form-section" v-if="isMenuType">
              <el-row :gutter="20">
                <!-- 页面模板 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    prop="template"
                    :label="$t('menu.dev.menu.field.template', '页面模板')"
                    :tooltipContent="
                      $t('menu.dev.menu.tip.template', '生成页面类型')
                    "
                  >
                    <ra-dict-select
                      v-model="formData.template"
                      code="sys_template"
                      :disabled="isEditMode"
                    ></ra-dict-select>
                  </el-form-item-plus>
                </el-col>
                <!-- 路由路径 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.route_path', '相对路径')"
                    prop="route_path"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.route_path',
                        '定义应用中不同页面对应的 URL 路径，例如：系统管理目录 /system，系统管理下的用户管理菜单 /system/user。',
                      )
                    "
                  >
                    <el-input
                      disabled
                      v-model="formData.route_path"
                      placeholder="/admin/system/user"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 路由名称 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.route_name', '路由名称')"
                    prop="route_name"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.route_name',
                        '如果需要开启缓存，需保证页面 defineOptions 中的 name 与此处一致，建议使用驼峰。',
                      )
                    "
                  >
                    <el-input
                      disabled
                      v-model="formData.route_name"
                      placeholder="AdminSystemUser"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 前端组件 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.component', '组件路径')"
                    prop="component"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.component',
                        '组件页面完整路径，相对于 src/views/admin/，如 system/user/index，缺省后缀 .vue',
                      )
                    "
                  >
                    <el-input
                      disabled
                      v-model="formData.component"
                      placeholder="src/views/admin/system/user/index"
                    >
                    </el-input>
                  </el-form-item-plus>
                </el-col>
                <!-- 保持状态 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.keep_alive', '缓存')"
                    :tooltipContent="
                      $t('menu.dev.menu.tip.keep_alive', '是否保存页面状态')
                    "
                    prop="keep_alive"
                  >
                    <ra-dict-select
                      v-model="formData.keep_alive"
                      code="yes_or_not_options"
                      type="radio"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 生成数据库表 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    prop="gen_table"
                    :label="$t('menu.dev.menu.field.gen_table', '创建表')"
                    :tooltipContent="
                      $t('menu.dev.menu.tip.gen_table', '是否自动创建数据库表')
                    "
                  >
                    <ra-dict-select
                      v-model="formData.gen_table"
                      code="yes_or_not_options"
                      type="radio"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 数据库连接 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.connect', '连接')"
                    prop="connect"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.connect',
                        '第一个下拉框用于选择数据库连接，如无跨数据库操作，选择默认即可',
                      )
                    "
                  >
                    <el-select style="width: 130px" v-model="formData.connect">
                      <el-option
                        v-for="item in connectOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item-plus>
                </el-col>
                <!-- 数据库表名 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.table_name', '表名')"
                    prop="table_name"
                  >
                    <el-input
                      style="width: 100%"
                      v-model="formData.table_name"
                      :placeholder="
                        $p('menu.dev.menu.field.table_name', '表名')
                      "
                    >
                    </el-input>
                  </el-form-item-plus>
                </el-col>
                <!-- 数据库表的主键列名 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.primary_key', '主键列')"
                    prop="primary_key"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.primary_key',
                        '请输入此表的主键字段名，默认为id',
                      )
                    "
                  >
                    <el-input
                      v-model="formData.primary_key"
                      :placeholder="
                        $p('menu.dev.menu.field.primary_key', '主键列')
                      "
                    >
                    </el-input>
                  </el-form-item-plus>
                </el-col>
                <!-- 菜单备注 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.remark', '备注')"
                    prop="primary_key"
                    :tooltipContent="
                      $t('menu.dev.menu.tip.remark', '请输入此菜单的备注信息')
                    "
                  >
                    <el-input
                      v-model="formData.remark"
                      type="textarea"
                      :placeholder="$p('menu.dev.menu.field.remark', '备注')"
                    >
                    </el-input>
                  </el-form-item-plus>
                </el-col>
              </el-row>
            </div>

            <!-- 目录 -->
            <div shadow="always" class="form-section" v-if="isCatalogType">
              <el-row :gutter="20">
                <!-- 路由路径 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.route_path', '相对路径')"
                    prop="route_path"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.route_path',
                        '定义应用中不同页面对应的 URL 路径，例如：系统管理目录 /system，系统管理下的用户管理菜单 /system/user。',
                      )
                    "
                  >
                    <el-input
                      v-model="formData.route_path"
                      placeholder="/admin/system/user"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 重定向地址 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.redirect', '重定向')"
                    prop="redirect"
                  >
                    <el-input
                      v-model="formData.redirect"
                      :placeholder="
                        $p('menu.dev.menu.field.redirect', '重定向')
                      "
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 总显示(无子菜单) -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.always_show', '总显示')"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.always_show',
                        '选择“是”，即使目录或菜单下只有一个子节点，也会显示父节点。选择“否”，如果目录或菜单下只有一个子节点，则只显示该子节点，隐藏父节点。如果是叶子节点，请选择“否”。',
                      )
                    "
                    prop="always_show"
                  >
                    <ra-dict-select
                      v-model="formData.always_show"
                      code="yes_or_not_options"
                      type="radio"
                    />
                  </el-form-item-plus>
                </el-col>
              </el-row>
            </div>

            <!-- iframe -->
            <div shadow="always" class="form-section" v-if="isIframeType">
              <el-row :gutter="20">
                <!-- 路由路径 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.route_path', '相对路径')"
                    prop="route_path"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.route_path',
                        '定义应用中不同页面对应的 URL 路径，例如：系统管理目录 /system，系统管理下的用户管理菜单 /system/user。',
                      )
                    "
                  >
                    <el-input
                      disabled
                      v-model="formData.route_path"
                      placeholder="/admin/system/user"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 路由名称 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.route_name', '路由名称')"
                    prop="route_name"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.route_name',
                        '如果需要开启缓存，需保证页面 defineOptions 中的 name 与此处一致，建议使用驼峰。',
                      )
                    "
                  >
                    <el-input
                      disabled
                      v-model="formData.route_name"
                      placeholder="AdminSystemUser"
                    />
                  </el-form-item-plus>
                </el-col>
                <!-- 组件地址 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.component', '组件路径')"
                    prop="component"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.component',
                        '组件页面完整路径，相对于 src/views/admin/，如 system/user/index，缺省后缀 .vue',
                      )
                    "
                  >
                    <el-input
                      disabled
                      v-model="formData.component"
                      placeholder="src/views/admin/system/user/index"
                    >
                    </el-input>
                  </el-form-item-plus>
                </el-col>
                <!-- 内嵌地址 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.redirect', '页面地址')"
                    prop="redirect"
                  >
                    <el-input
                      v-model="formData.redirect"
                      :placeholder="
                        $p('menu.dev.menu.field.redirect', '页面地址')
                      "
                    />
                  </el-form-item-plus>
                </el-col>
              </el-row>
            </div>

            <!-- extlink -->
            <div shadow="always" class="form-section" v-if="isExtlinkType">
              <el-row :gutter="20">
                <!-- 外链地址 -->
                <el-col :xs="24" :sm="12" :md="12">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.extlink', '外链地址')"
                    prop="extlink"
                    :tooltipContent="
                      $t(
                        'menu.dev.menu.tip.extlink',
                        '请输入需要跳转到的目的互联网地址',
                      )
                    "
                  >
                    <el-input
                      v-model="formData.redirect"
                      :placeholder="
                        $p('menu.dev.menu.field.extlink', '外链地址')
                      "
                    />
                  </el-form-item-plus>
                </el-col>
              </el-row>
            </div>

            <!-- 多语言配置 -->
            <div shadow="always" class="form-section" v-if="enableLanguage">
              <ra-multi-lang
                v-model="formData.translations"
                :languages="languageList"
                :required="false"
                :prop-prefix="'formData'"
                :show-key-input="true"
                :key-value="formData.key"
                :key-prop="'key'"
                :loading="loading"
                @update:keyValue="handleKeyUpdate"
                @getTransData="getTransData"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane
            :label="$t('menu.dev.menu.tabs.extend', '扩展信息')"
            name="extend"
          >
            <div shadow="always" class="form-section">
              <el-row :gutter="20">
                <!-- 扩展配置 -->
                <el-col :xs="24" :sm="24" :md="24">
                  <el-form-item-plus
                    :label="$t('menu.dev.menu.field.config', '高级配置')"
                    prop="config"
                    label-position="top"
                  >
                    <ra-object-editor v-model="formData.config" />
                  </el-form-item-plus>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- footer -->
      <template #footer>
        <div>
          <el-button type="info" @click="cancelHandler">
            {{ $t('common.action.cancel', '取消') }}
          </el-button>
          <el-button type="warning" @click="resetHandler">
            {{ $t('common.action.reset', '重置') }}
          </el-button>
          <el-button type="primary" @click="submitHandler" :loading="loading">
            {{ $t('common.action.confirm', '确定') }}
          </el-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup>
import MenuAPI from '@/api/admin/dev/menu';
import LangAPI from '@/api/admin/admin/i18n';
import { useDictStore, useUserStore } from '@/store';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { ElMessage } from 'element-plus';
import { MenuTypeEnum } from '@/enums';
import {
  FORM_MODE,
  DEFAULT_CONNECT,
  VALIDATION_ERROR_NAME,
} from './composables/constants';

import { useFormValidation } from './composables/useFormValidation';
import { useMenuFormData } from './composables/useFormData';
import { generateMenuDetails } from './composables/utils';

defineOptions({
  name: 'MenuUpdate',
  inheritAttrs: false,
});

// Props定义
const props = defineProps({
  mode: {
    type: String,
    default: FORM_MODE.ADD,
    validator: (value) => Object.values(FORM_MODE).includes(value),
  },
});

// 字典
const dictStore = useDictStore();
// 用户
const userStore = useUserStore();
// 表单验证
const { validateForm, clearValidation } = useFormValidation();
// 表单数据管理
const { formData, initialFormData, resetFormData, initFormData } =
  useMenuFormData();

// 表单数据是否载入完成
const isLoaded = ref(false);
// 定义可触发事件
const emit = defineEmits(['reload']);
// 是否显示载入效果
const loading = ref(false);
// 翻译加载状态
const translationLoading = ref(false);
// 是否显示
const show = ref(false);
// 选项卡
const activeTab = ref('basic');
// 表单对象
const refForm = ref(null);
// 数据库连接
const connectOptions = ref([]);
// 多语言列表
const languageList = ref([]);

// 计算属性：模态框标题
const modalTitle = computed(() => {
  return props.mode === FORM_MODE.ADD
    ? $t('common.action.add', '新增')
    : $t('common.action.update', '修改');
});

// 计算属性：是否为编辑模式
const isEditMode = computed(() => props.mode === FORM_MODE.EDIT);

// 计算属性：菜单类型判断
const isMenuType = computed(() => formData.value.type === MenuTypeEnum.MENU);
const isCatalogType = computed(
  () => formData.value.type === MenuTypeEnum.CATALOG,
);
const isIframeType = computed(
  () => formData.value.type === MenuTypeEnum.IFRAME,
);
const isExtlinkType = computed(
  () => formData.value.type === MenuTypeEnum.EXTLINK,
);
const enableLanguage = computed(() => formData.value.lang === 1);

// 表单验证规则
const formRules = reactive({
  pid: [
    {
      required: true,
      message: $p('menu.dev.menu.field.pid', '父菜单', 'select'),
      trigger: 'blur',
    },
  ],
  name: [
    {
      required: true,
      message: $p('menu.dev.menu.field.name', '名称'),
      trigger: 'blur',
    },
    {
      max: 50,
      message: $t(
        'common.message.validate.max',
        '{field}长度不能超过{max}个字符',
        {
          field: $t('menu.dev.menu.field.name', '名称'),
          max: 50,
        },
      ),
      trigger: 'blur',
    },
  ],
  controller: [
    {
      required: true,
      message: $p('menu.dev.menu.field.controller', '控制器'),
      trigger: 'blur',
    },
    {
      pattern: /^[a-zA-Z0-9/]+$/,
      message: '仅允许使用字母数字和斜杠',
    },
    {
      trigger: 'blur',
      validator: (_, value, callback) => {
        if (!checkStringFormat(value)) {
          callback(
            new Error(
              $t(
                'common.message.validate.format',
                '{field}格式不正确，目录部分只能首字母大写',
                {
                  field: $t('menu.dev.menu.field.controller', '控制器'),
                },
              ),
            ),
          );
        } else {
          callback();
        }
      },
    },
  ],
  connect: [
    {
      trigger: 'blur',
      validator: (_, value, callback) => {
        if (formData.value?.gen_table === 1 && !value) {
          callback(
            new Error($p('menu.dev.menu.field.connect', '连接', 'select')),
          );
        } else {
          callback();
        }
      },
    },
  ],
  table_name: [
    {
      trigger: 'blur',
      validator: (_, value, callback) => {
        if (formData.value?.gen_table === 1 && !value) {
          callback(new Error($p('menu.dev.menu.field.table_name', '表名')));
        } else {
          callback();
        }
      },
    },
  ],
  // iframe_url: [
  //   {
  //     required: true,
  //     message: $p('menu.dev.menu.field.iframe_url', '页面地址'),
  //     trigger: 'blur',
  //   },
  // ],
  extlink: [
    {
      required: true,
      message: $p('menu.dev.menu.field.extlink', '外链URL'),
      trigger: 'blur',
    },
  ],
  template: [
    {
      required: true,
      validator: (_, value, callback) => {
        if (formData.value?.type === MenuTypeEnum.MENU && !value) {
          callback(new Error($p('menu.dev.menu.field.template', '页面模板')));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});

/**
 * 方法
 */

function checkStringFormat(str) {
  const parts = str.split('/');

  if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) {
    return false; // Handle empty string or just a slash
  }

  for (let i = 0; i < parts.length; i++) {
    const part = parts[i];

    if (part.length === 0) {
      return false; // Empty parts are not allowed (e.g., "A//B")
    }

    const firstChar = part[0];

    // All parts must start with an uppercase letter
    if (
      firstChar.toUpperCase() !== firstChar ||
      firstChar.toLowerCase() === firstChar
    ) {
      return false;
    }

    if (i < parts.length - 1) {
      // For non-last parts, all subsequent characters must be lowercase
      for (let j = 1; j < part.length; j++) {
        const char = part[j];
        if (char.toLowerCase() !== char || char.toUpperCase() === char) {
          return false;
        }
      }
    } else {
      // For the last part, the first character must be uppercase (already checked).
      // The rest of the characters can be any case (uppercase or lowercase).
      // So, no further case checks are needed for characters after the first in the last part.
    }
  }

  return true;
}

// 重置表单
const resetForm = () => {
  if (refForm.value) {
    refForm.value.resetFields();
  }
  resetFormData();
};

// 获取翻译数据
const getTransData = async () => {
  if (!formData.value.key) {
    ElMessage.error($p('menu.dev.menu.field.lang_key', '语言键'));
    return;
  }

  try {
    translationLoading.value = true;
    const { data } = await LangAPI.getTransData({ key: formData.value.key });
    formData.value.translations = data;
    ElMessage.success(
      $t('common.message.success.general', '{action}成功！', {
        action: $t('common.action.load', '加载'),
      }),
    );
  } catch (error) {
    console.error('Error loading translation data:', error);
  } finally {
    translationLoading.value = false;
  }
};

// 加载基础数据
const loadBaseData = async () => {
  try {
    const [connects, languages] = await Promise.all([
      MenuAPI.getConnects(),
      LangAPI.getLangList(),
    ]);
    connectOptions.value = connects.data;
    languageList.value = languages.data.languages;
  } catch (error) {
    console.error('Error loading base data:', error);
    ElMessage.error($t('common.message.info.load_failed', '加载失败！'));
  }
};

// 滚动到第一个验证错误的字段
const scrollToFirstError = () => {
  nextTick(() => {
    const firstErrorField = document.querySelector(
      'div.is-error .el-form-item__content',
    );
    if (firstErrorField) {
      firstErrorField.scrollIntoView({
        behavior: 'smooth',
        block: 'center',
      });
    }
  });
};
// 处理语言键更新
const handleKeyUpdate = (newKey) => {
  formData.value.key = newKey;
};

/**
 * 操作句柄
 */
// 提交操作（统一处理新增和编辑）
const submitHandler = async () => {
  try {
    await validateForm(refForm.value); // 使用封装的验证函数
    loading.value = true;

    const postData = { ...formData.value };
    console.log('Form Data :', postData);

    if (props.mode === FORM_MODE.ADD) {
      await MenuAPI.add(postData);
      ElMessage.success(
        $t('common.message.success.general', '{action}成功！', {
          action: $t('common.action.add', '新增'),
        }),
      );
    } else {
      await MenuAPI.update(postData);
      ElMessage.success(
        $t('common.message.success.general', '{action}成功！', {
          action: $t('common.action.update', '修改'),
        }),
      );
    }

    // 重新加载字典
    dictStore.refreshDictionaryCache();
    // 更新用户权限
    userStore.getUserInfo();

    resetForm();
    show.value = false;
    emit('reload');
  } catch (error) {
    console.error(`Error in ${props.mode}Handler:`, error);

    // 如果是验证错误，滚动到第一个错误字段
    if (error.name === VALIDATION_ERROR_NAME) {
      scrollToFirstError();
      return;
    }

    // 处理API错误
    const errorMessage =
      error.response?.data?.message ||
      (props.mode === FORM_MODE.ADD
        ? $t('common.message.failed.general', '{action}失败！', {
            action: $t('common.action.add', '新增'),
          })
        : $t('common.message.failed.general', '{action}失败！', {
            action: $t('common.action.update', '修改'),
          }));

    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 取消操作
const cancelHandler = () => {
  resetForm();
  show.value = false;
};

// 重置表单操作
const resetHandler = () => {
  resetForm();
};

// 监听controller/gen_table的变化
watch(
  () => [formData.value.controller, formData.value.gen_table],
  ([newController, newgen_table], [oldController, oldgen_table] = []) => {
    if (newController || newgen_table !== oldgen_table) {
      try {
        if (newController) {
          const details = generateMenuDetails(newController);
          Object.assign(formData.value, {
            code: details.code,
            route_name: details.route_name,
            route_path: details.route_path,
            route_path_full: details.route_path_full,
            component: details.component,
            table_name: newgen_table ? details.table_name : '',
            key: details.langKey,
          });
        }
      } catch (error) {
        console.error('Error generating route details:', error);
      }
    }
  },
);

/**
 * 暴露方法
 */
defineExpose({
  async show(id) {
    // 操作类型
    if (props.mode === FORM_MODE.ADD) {
      // console.log('显示添加对话框，所属菜单ID:', id);
      // 设置所属字典
      if (id) {
        formData.value.menu_id = id;
      }
      // 加载基础数据
      loadBaseData();
      // 初始化表单数据
      initFormData();
      // 显示组件
      show.value = true;
      // 重置表单
      nextTick(() => {
        resetForm();
        isLoaded.value = true;
      });
    } else {
      // 编辑模式：加载数据
      // console.log('显示编辑对话框，ID:', id);
      const params = { id };
      loading.value = true;

      try {
        const { data } = await MenuAPI.getFormData(params);
        // 加载基础数据
        loadBaseData();
        // 初始化表单数据
        initFormData(data);
        // 显示组件
        show.value = true;
        nextTick(() => {
          // 重置表单验证状态
          clearValidation(refForm.value); // 使用封装的清除验证函数
          // 数据是否载入完成
          isLoaded.value = true;
        });
      } catch (error) {
        console.error('Error loading form data:', error);
        ElMessage.error($t('common.message.info.load_failed', '加载失败！'));
      } finally {
        loading.value = false;
      }
    }
  },
});
</script>

<style lang="scss" scoped>
.form-section {
  margin: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}
</style>
